package org.spbsu.apco.common.data.core;

import org.spbsu.apco.common.properties.ApplicationPropertiesManager;
import org.spbsu.apco.common.properties.PropertyKey;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * User: solozobov
 * Date: 15.11.12
 */

public class FileData implements Data{
    private static final File storage = new File(ApplicationPropertiesManager.getProperty(PropertyKey.FILE_STORAGE_DIR));
    static {
        if (!storage.isDirectory()) {
            //noinspection ResultOfMethodCallIgnored
            storage.delete();
        }
        if (!storage.exists()) {
            //noinspection ResultOfMethodCallIgnored
            storage.mkdir();
        }
    }

    public final String pathInStorage;
    public final File file;

    public FileData(final String pathInStorage, final File file) {
        this.pathInStorage = pathInStorage;
        this.file = file;
    }

    public FileData(final byte[] representation) throws IOException {
        int pathLength = representation[0] << 24 | representation[1] << 16 | representation[2] << 8 | representation[3];
        final byte[] pathBytes = new byte[pathLength];
        System.arraycopy(representation, 4, pathBytes, 0, pathLength);
        this.pathInStorage = new String(pathBytes, "UTF-8");

        this.file = new File(storage, this.pathInStorage);
        final int fileLength = representation.length - 4 - pathLength;
        final FileOutputStream out = new FileOutputStream(this.file);
        out.write(representation, 4 + pathLength, fileLength);
        out.close();
    }

    @Override
    public byte[] serialize() throws Exception {
        final byte[] pathBytes = pathInStorage.getBytes("UTF-8");
        final int pathLength = pathBytes.length;

        final FileInputStream in = new FileInputStream(file);
        final int fileLength = in.available();

        final byte[] result = new byte[4 + pathLength + fileLength];
        result[0] = (byte) (pathLength >> 24);
        result[1] = (byte) (pathLength >> 16 & 0xFF);
        result[2] = (byte) (pathLength >> 8 & 0xFF);
        result[3] = (byte) (pathLength & 0xFF);
        System.arraycopy(pathBytes, 0, result, 4, pathLength);
        //noinspection ResultOfMethodCallIgnored
        in.read(result, 4 + pathLength, fileLength);
        in.close();

        return result;
    }

}
